package com.hsy.linemoney.apiservice;

import com.hsy.linemoney.requests.RequestQueue;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 网络请求基类
 * Created by MartinKent on 2016/9/9.
 */
public class BasicService<T> {
    private final RequestQueue<T> queue;
    private RequestQueue.OnRequestExecutedListener mOnRequestExecutedListener;

    protected BasicService() {
        queue = new RequestQueue<>();
    }

    public void setRequestExecutedListener(RequestQueue.OnRequestExecutedListener listener) {
        this.mOnRequestExecutedListener = listener;
    }

    public void invoke(final int what, final String api, final JSONObject params, final Callback<T> callback, boolean... checkStatusCode) {
        try {
            JSONObject p = null == params ? new JSONObject() : params;
            p.put("languageCd", LineMoneyContext.getLocalLanguagePair().locale.getLanguage());
            p.put("companyId", LineMoneyContext.getLiferay_company_id());
            p.put("groupId", LineMoneyContext.getLiferay_group_id());
            if (LineMoneyContext.isLoggedIn()) {
                p.put("userId", LineMoneyContext.getLoggedUser().getUserId());
            }
            queue.addTask(what, api, p, callback, checkStatusCode);
            queue.start(mOnRequestExecutedListener);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void cancel() {
        if (null != queue) {
            queue.clearTask();
        }
    }
}
